import { unref, type Ref } from "vue";
import type { ISearchOptions } from "./types";

/**
 * 显示搜素面板
 */

export default function useSearch(
  AMapFactoryRef: Ref<AMap.Map | null>,
  mapInstenceRef: Ref<AMap.Map | null>
) {
  /**
   * 搜索地点
   * @param value 搜索关键字
   * @param options 其他选项
   */
  function localSearch(
    value: string | Ref<string>,
    options: ISearchOptions = { pageIndex: 1, pageSize: 5 }
  ): Promise<{ status: string; result: object }> {
    const keyword = unref(value);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const placeSearch = new AMapFactoryRef.value!.PlaceSearch({
      version: "2.0",
      pageSize: options.pageSize, //单页显示结果条数
      pageIndex: options.pageIndex, //页码
      citylimit: false, //是否强制限制在设置的城市内搜索

      map: mapInstenceRef.value, //展现结果的地图实例
      // panel: "my-panel", //结果列表将在此容器中进行展示。
      autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
    });

    // 地图查询结果的 marker 点击事件
    // placeSearch.on(
    //   "markerClick",
    //   function (data: { data: object; marker: { dom: HTMLElement } }) {
    //     const poi = data.data;
    //     const container = data.marker.dom;
    //     uni.$emit(markerClicked, {
    //       poi,
    //       container,
    //     });
    //   }
    // );

    return new Promise((resolve) => {
      placeSearch.search(keyword, function (status: string, result: object) {
        removeSearchMarker();
        resolve({
          status,
          result,
        });
      });
    });
  }

  function removeSearchMarker() {
    const markers = mapInstenceRef.value?.getAllOverlays();

    markers?.forEach((marker) => {
      if (!marker._opts.extData?.flag) {
        mapInstenceRef.value?.remove(marker);
      }
    });
  }

  return {
    localSearch,
    removeSearchMarker,
  };
}
